<template>
	<div class="articleList" ref="articleListItem">
		<div class="articleList-item" v-for="list in articleList">
			<li v-for="item in list" @click="$router.push('/article?id='+item._id)">
				<div>

					<div class="image-list">
						<div class="img" v-if="item.imageSrc.length">
							<img @error="imgError" :src="item.imageSrc[0]" v-lazy="item.imageSrc[0]" />
						</div>
					</div>
					<div class="title">{{ item.title }}</div>
					<div class="info">
						<span>{{ item.author }}</span>
						<span> {{ item.comment }}评论</span>
						<span>{{ item.timeStr }}</span>
					</div>
				</div>
			</li>
		</div>

	</div>
</template>

<script>
	import config from '@/config'
	export default {
		name: "ArticleList",
		filters: {
			imgFilter(img) {
				if (img.includes(config.baseImgUrl) || img.includes(config.baseImgUrls)) {
					return img + '?imageMogr2/thumbnail/!50p'
				}
				return img
			}
		},
		data() {
			return {
				articleList: [
					[],
					[]
				],
				arrHeight: [0, 0],
				itemW: 0
			}
		},
		props: {
			newData: {
				type: Array,
				default: () => []
			}
		},
		mounted() {
			this.itemW = parseInt(getComputedStyle(this.$refs.articleListItem, null).width) / 2 - 40;


		},
		watch: {
			newData(arr) {
				if (arr.length === 0) {
					this.articleList =  [
						[],
						[]
					]
				};

				let taskList = arr.map(v => v.imageSrc).map(v => {
					return new Promise((resolve, reject) => {
						if (v.length === 0) {
							resolve(0)
						} else {
							let img = new Image();
							img.src = v[0]
							img.onload = () => {
								resolve(img.width / img.height * this.itemW)
							}
							img.onerror = function() {

								resolve(0)
							}

						}

					})

				});


				Promise.all(taskList).then(res => {

					arr.forEach((v, k) => {
						v.h = res[k];

						let max = Math.min(...this.arrHeight);
						let index = this.arrHeight.findIndex(v => v == max);

						this.arrHeight[index] += v.h;
						this.articleList[index].push(v);
						console.log(this.arrHeight)

					});
				})




			}
		}
	}
</script>

<style lang="scss">
	.articleList {
		padding: 0 10px;
		display: flex;
		flex-flow: row wrap;
		justify-content: space-between;

		.articleList-item {

			width: 170px;
			padding: 10px 0;
			border-bottom: 1px solid #eee;

		}


		li {

			width: 100%;
		}

		.title {
			color: #222;
			font-size: 18px;
			line-height: 25px;
			white-space: pre-wrap;
			word-break: break-all;
			overflow: hidden;
			width: 100%;
		}

		.articleItem-single {
			display: flex;
		}

		.image-list {
			border-radius: 1px;
			display: flex;
			justify-content: space-between;
			overflow: hidden;

			.img {
				width: 100%;
				height: auto;
			}

			img {
				width: 100%;
				height: auto;
			}
		}



		.info {
			color: #999;
			font-size: 12px;
			line-height: 16px;
			margin-top: 8px;
		}
	}
</style>
